/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sirtet.netplay;

/**
 * This is a final class providing a list of strings used in netplay protocol.
 * @author guangwei.zhu
 */
public final class ClientResponse {

    private ClientResponse() {     // No instantiation
    }

    public static final String READY = "READY";
    public static final String CHANGE_GAMETYPE = "CHANGE_GAMETYPE";
    public static final String PREFIX_PLAYERID = "ID=";
    public static final String PREFIX_GAMETYPE = "GAMETYPE=";

    public static final String construct(String prefix, String data) {
        return prefix + data;
    }

    public static final String parse(String prefix, String message) {
        int len = prefix.length();
        if (message.length() < len || !message.substring(0, len).equals(prefix)) {
            return null;    // not matching
        }
        return message.substring(len);
    }

    public static void respond(NetworkPlayer source, String data) {
        try {
            if (data.equals(ServerResponse.ASK_PLAYERID)) {
                source.getCommunicator().send(construct(PREFIX_PLAYERID, source.id()));
            }
            if (data.equals(ServerResponse.ASK_GAMETYPE)) {
                source.getCommunicator().send(construct(PREFIX_GAMETYPE, source.gameType()));
            } else if (data.equals(ServerResponse.ACCEPTED)) {
                if (source instanceof SynchronizedPlayer) {
                    ((SynchronizedPlayer) source).setSync(true);
                }
            } else if (data.equals(ServerResponse.ASK_READY)) {
                if (source.ready()) {   // If ready, give back notification
                    source.getCommunicator().send(READY);
                }
            }
        } catch (Exception ex) {
        }
    }
}
